package com.bigfans.catalogservice.api.mgr;

import com.bigfans.catalogservice.model.AttributeOption;
import com.bigfans.catalogservice.model.AttributeValue;
import com.bigfans.catalogservice.model.SpecOption;
import com.bigfans.catalogservice.service.attribute.AttributeOptionService;
import com.bigfans.catalogservice.service.attribute.AttributeValueService;
import com.bigfans.framework.annotations.NeedLogin;
import com.bigfans.framework.utils.CollectionUtils;
import com.bigfans.framework.utils.StringHelper;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
public class AttributeManageApi extends BaseController {

    @Autowired
    private AttributeOptionService attributeOptionService;
    @Autowired
    private AttributeValueService attributeValueService;

    @PostMapping(value = "/attributeOption")
    @NeedLogin(roles = {"operator" , "admin"})
    public RestResponse createAttributeOption(@RequestBody AttributeOption option) throws Exception {
        attributeOptionService.create(option);
        return RestResponse.ok();
    }

    @PostMapping(value = "/attributeOption/{id}")
    @NeedLogin(roles = {"operator" , "admin"})
    public RestResponse update(@RequestBody AttributeOption attributeOption , @PathVariable(value = "id") String id) throws Exception {
        attributeOption.setId(id);
        attributeOptionService.update(attributeOption);
        return RestResponse.ok();
    }

    @GetMapping(value = "/attributeOptions/{id}")
    @NeedLogin(roles = {"operator" , "admin"})
    public RestResponse createAttributeOption(@PathVariable(value = "id") String id) throws Exception {
        AttributeOption attributeOption = attributeOptionService.load(id);
        return RestResponse.ok(attributeOption);
    }

    @GetMapping(value = "/attributeValues")
    @NeedLogin(roles = {"operator", "admin"})
    public RestResponse listAttributeValues(@RequestParam(value = "optionId") String optionId) throws Exception {
        List<AttributeValue> attributeValues = attributeValueService.listByOptionId(optionId);
        return RestResponse.ok(attributeValues);
    }

    @GetMapping(value = "/attributeOptions")
    @NeedLogin(roles = {"operator", "admin"})
    public RestResponse listAttributes(
            @RequestParam(value = "catId", required = false) String catId
    ) throws Exception {
        List<AttributeOption> attributes = attributeOptionService.listByCategory(catId);
        return RestResponse.ok(attributes);
    }

    @DeleteMapping(value = "/attributeOption/{id}")
    @NeedLogin(roles = {"operator" , "admin"})
    public RestResponse delete(@PathVariable(value = "id") String id) throws Exception {
        attributeOptionService.delete(id);
        return RestResponse.ok();
    }
}
